package com.donica.wamstest.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.donica.wamstest.common.Constant;
import com.donica.wamstest.entity.CommonFindVO;
import com.donica.wamstest.entity.FileDTO;
import com.donica.wamstest.entity.FileVO;
import com.donica.wamstest.entity.FilelistVO;
import com.donica.wamstest.entity.PackageDTO;
import com.donica.wamstest.entity.PageResult;
import com.donica.wamstest.entity.PlaylistVO;
import com.donica.wamstest.entity.ProgramfileVO;
import com.donica.wamstest.entity.ReturnMessage;
import com.donica.wamstest.mapper.FileMapper;
import com.donica.wamstest.utils.CommonUtil;
import com.donica.wamstest.utils.FileHandleUtil;
import com.donica.wamstest.utils.PlaylistUtil;

@Service
public class CloudFileService {

	@Autowired
	FileMapper fileMapper;
	private ArrayList<FileVO> publicFiles = new ArrayList<FileVO>();

	@Value("${public.path}")
	private String publicPath;

	public ArrayList<FileVO> ScanFiles() throws Exception {

		publicFiles.clear();
		publicFiles = FileHandleUtil.scanFilesWithRecursion(publicPath);

		// 修改为相对地址
		for (FileVO fileVO : publicFiles) {

			fileVO.setUri(fileVO.getUri().substring(publicPath.length() + 1));
		}

		return publicFiles;
	}

	// 查询节目包
	public void ScanProgram() throws Exception {
		String pathTmp = publicPath + File.separator + Constant.DIR_PROGRAM;

		List<String> dirs = new ArrayList<String>();
		FileHandleUtil.scanDirsWithRecursion(pathTmp, dirs);

		List<PackageDTO> pDtos = new ArrayList<PackageDTO>();
		for (String dir : dirs) {
			PackageDTO pDto = ScanFiles1(dir);
			pDto.setPlaylist("");
			pDto.setFilelist("");
			pDtos.add(pDto);
		}

		fileMapper.deleteProgramPackageExclude(pDtos);
	}

	// scan 软件包
	public void ScanSoftware() throws Exception {
		String pathTmp = publicPath + File.separator + Constant.DIR_SOFTWARE;

		List<FileDTO> files = new ArrayList<FileDTO>();
		FileHandleUtil.scanFilesWithRecursion(pathTmp, files);

		List<PackageDTO> pDtos = new ArrayList<PackageDTO>();
		
		for (FileDTO file : files) {
			PackageDTO pDto = new PackageDTO();
			pDto.valueOf(file);
			pDto.setId(CommonUtil.get32UUID());
			pDtos.add(pDto);
		}
		fileMapper.InsertSoftware(pDtos);
	}

	public ReturnMessage searchProgramPackage(CommonFindVO vo) {
		ReturnMessage rtnMsg = new ReturnMessage();
		try {
			long total = fileMapper.searchProgramPackageCount(vo);
			List<PackageDTO> result = fileMapper.searchProgramPackage(vo);
			PageResult pageResult = new PageResult();
			pageResult.setTotalCount(total);
			pageResult.setPageSize(vo.getPageSize());
			pageResult.setCurrPage(vo.getCurrPage());

			// 转换成json
			for (PackageDTO packageDTO : result) {
				packageDTO.setPlaylist(JSON.parse(packageDTO.getPlaylist().toString()));
				packageDTO.setFilelist(JSON.parse(packageDTO.getFilelist().toString()));
			}

			pageResult.setResult(result);

			rtnMsg.setResult(pageResult);
		} catch (Exception e) {
			rtnMsg.setCode(ReturnMessage.FAIL);
			rtnMsg.setMsg(e.getMessage());
		}

		return rtnMsg;
	}
	
	public ReturnMessage searchSoftwarePackage(CommonFindVO vo) {
		ReturnMessage rtnMsg = new ReturnMessage();
		try {
			long total = fileMapper.searchSoftwarePackageCount(vo);
			List<PackageDTO> result = fileMapper.searchSoftwarePackage(vo);
			PageResult pageResult = new PageResult();
			pageResult.setTotalCount(total);
			pageResult.setPageSize(vo.getPageSize());
			pageResult.setCurrPage(vo.getCurrPage());
			pageResult.setResult(result);

			rtnMsg.setResult(pageResult);
		} catch (Exception e) {
			rtnMsg.setCode(ReturnMessage.FAIL);
			rtnMsg.setMsg(e.getMessage());
		}

		return rtnMsg;
	}
	
	

	public PackageDTO ScanFiles1(String dir) throws Exception {

		String playlistFile = publicPath + File.separator + Constant.DIR_PROGRAM + File.separator + dir + File.separator
				+ Constant.PLAYLIST_FILE;
		PlaylistVO playlistVO = PlaylistUtil.parsePlaylist(playlistFile);

		List<PackageDTO> pDtos = new ArrayList<PackageDTO>();
		PackageDTO pDto = new PackageDTO();
		pDto.valueOf(playlistVO);
		pDto.setId(CommonUtil.get32UUID());
		pDto.setPlaylist(JSONObject.toJSONString(playlistVO));

		// 计算节目时长
		long duration = 0;
		HashMap<String, Object> tmpMap = new HashMap<String, Object>();
		for (FilelistVO filelistVO : playlistVO.getFileList()) {
			for (ProgramfileVO fileVO : filelistVO.getFiles()) {
				if (tmpMap.get(fileVO.getFilename()) == null) {
					duration += fileVO.getDuration();
					tmpMap.put(fileVO.getFilename(), fileVO.getDuration());
				}
			}
		}
		pDto.setDuration(duration);

		// 遍历目录获取文件列表
		List<FileDTO> fileDtos = getPackageFiles(dir, playlistVO);
		pDto.setFilelist(JSONObject.toJSONString(fileDtos));

		// 计算包size
		long size = 0;
		for (FileDTO fileDTO : fileDtos) {
			size += fileDTO.getSize();
		}
		pDto.setSize(size);

		pDtos.add(pDto);
		fileMapper.InsertPackage(pDtos);
		// fileMapper.InsertFiles(fileDtos);

		List<ProgramfileVO> fileVOs = new ArrayList<ProgramfileVO>();

		for (FilelistVO filelistVO : playlistVO.getFileList()) {

			for (ProgramfileVO fileVO : filelistVO.getFiles()) {
				ProgramfileVO fileTmpVO = new ProgramfileVO();
				fileTmpVO.valueOf(fileVO);
				fileTmpVO.setId(CommonUtil.get32UUID());
				fileTmpVO.setPackage_index(pDto.getId());
				fileVOs.add(fileTmpVO);
			}
		}

		// fileMapper.InsertProgramfiles(fileVOs);

		return pDto;
	}

	public List<FileDTO> getPackageFiles(String versionDir, PlaylistVO playlistVO) throws Exception {

		List<FileDTO> dtos = new ArrayList<FileDTO>();

		// 记录重复目录
		HashMap<String, Object> tmpMap = new HashMap<String, Object>();

		// 获取playlist文件
		String pathPackage = publicPath + File.separator + Constant.DIR_PROGRAM + File.separator + versionDir;

		// 遍历获取节目列表下文件
		FileHandleUtil.scanFilesWithRecursion(pathPackage, dtos);

		// 遍历获取节目内容文件
		for (FilelistVO filelistVO : playlistVO.getFileList()) {

			for (ProgramfileVO fileVO : filelistVO.getFiles()) {
				String pathTmp = pathPackage + File.separator + fileVO.getProgramname();

				if (tmpMap.get(pathTmp) == null) {
					FileHandleUtil.scanFilesWithRecursion(pathTmp, dtos);
					tmpMap.put(pathTmp, 1);
				}

			}
		}

		int index = 0;

		// 把绝对路径转换成相对路径
		String publicPathString = new File(publicPath).getAbsolutePath();

		for (FileDTO dto : dtos) {
			dto.setId(CommonUtil.get32UUID());
			dto.setIndex(index++);
			dto.setPackage_index(playlistVO.getVersion());
			dto.setUri(dto.getUri().substring(publicPathString.length() + File.separator.length()));
		}

		return dtos;
	}
}
